<template>
  <div class="search-advice">
    <van-cell-group inset>
      <van-cell
        icon="search"
        v-for="(suggest, index) in searchSuggestValue"
        :key="index"
        @click="$emit('search', suggest.title)"
      >
        <!-- :title="suggest.title" -->
        <div slot="title" v-html="replaceHigh(suggest.title)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>
<script>
import { getSearchSuggest } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'search-advice',
  data () {
    return {
      searchSuggestValue: []
    }
  },
  created () {
    // this.onSearch()
  },
  methods: {
    // 搜索建议高亮
    replaceHigh (title) {
      const highlight = this.searchValue
      // 替换所有出现的,忽略大小写
      return title.replace(
        new RegExp(highlight, 'gi'),
        `<span style="color: red;">${highlight}</span>`
      )
      // 替换出现的第一个
      // return title.replace(
      //   new RegExp(highlight, 'i'),
      //   `<span style="color: red;">${highlight}</span>`
      // )
    }
  },
  components: {},
  props: {
    searchValue: {
      type: String,
      required: true
    }
  },
  watch: {
    searchValue: {
      handler: debounce(async function () {
        const searchContent = this.searchValue
        if (!searchContent) {
          return
        }
        const { data } = await getSearchSuggest(searchContent)
        this.searchSuggestValue = data.data
      }, 300),
      immediate: true
    }
  },
  computed: {},
  mounted () {}
}
</script>

<style lang="less" scoped></style>
